<template>
  <BasicModal
    v-bind="$attrs"
   :title="t('sys.script.details')"
    :width="modalWidth"
    @register="registerModal"
    :showOkBtn="false"
  >
    <BasicTable @register="registerTable">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: t('sys.configuration.startUsing'),
                tooltip: t('sys.configuration.startUsing'),
                onClick: handleEnable.bind(null, record),
                disabled: record.isCurrent, // 在 isCurrent 为 true 时禁用按钮
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { getOtherVersionsAPI, setselectVersionAPI } from '@/api/demo/script';
  import { columns } from './account.data';
  import { useI18n } from "@/hooks/web/useI18n";

  const { t } = useI18n();
  const modalWidth = ref('50%'); // 可以是像 600 这样的像素值，或者百分比 '50%'
  const tableData = ref([]); // 定义一个响应式变量来存储表格数据
  const emit = defineEmits(['success']);
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    const record = data.record; // 从 data 中获取 record 对象
    setModalProps({ confirmLoading: true }); // 显示加载状态

    try {
      const result = await getOtherVersionsAPI(record.name);
      tableData.value = result.data; // 将接口返回的数据赋值给表格数据
    } catch (error) {
      console.error('Failed to fetch other versions:', error);
    } finally {
      setModalProps({ confirmLoading: false }); // 隐藏加载状态
    }
  });

  const [registerTable, { setTableData }] = useTable({
    dataSource: tableData, // 使用响应式变量作为表格数据源
    columns,
    showTableSetting: true,
    bordered: true,
    showIndexColumn: false,
    actionColumn: {
      width: 50,
      title: t('sys.configuration.action'),
      dataIndex: 'action',
    },
  });

  async function handleEnable(record) {
    setModalProps({ confirmLoading: true }); // 显示加载状态
    try {
      const result = await setselectVersionAPI(record);
      emit('success', result); // 触发 success 事件
      record.isCurrent = true; // 更新 isCurrent 字段
      setTableData(tableData.value); // 更新表格数据
    } catch (error) {
      console.error('Failed to enable version:', error);
    } finally {
      setModalProps({ confirmLoading: false }); // 隐藏加载状态
      closeModal(); // 关闭弹出框
    }
  }
</script>
